package com.nulldev.util.web.nTubeExtensions.Redwood.pages;

import java.time.Duration;
import java.util.regex.Pattern;

import com.nulldev.util.JVM.JVM;
import com.nulldev.util.VariableAPI.StringsUtil;
import com.nulldev.util.data.variable;
import com.nulldev.util.io.file.FileUtil;
import com.nulldev.util.web.HttpClient.HttpClient;
import com.nulldev.util.web.HttpServer3.Response;
import com.nulldev.util.web.HttpServer3.pages.v3.HttpPage3;
import com.nulldev.util.web.YouTubeExtractor.YouTubeExtractor;
import com.nulldev.util.web.nTube.resources.project_redwood.RedwoodResource;
import com.nulldev.util.web.nTubeExtensions.Redwood.Redwood;

public class RedwoodPlayerCSSFile extends HttpPage3 {

	public RedwoodPlayerCSSFile() {
		super("/resources/redwood/player.css");
		this.setCachingMethod(CachingMethod.SHORT_CACHE);
	}

	public static RedwoodPlayerCSSFile make() throws Exception {
		YouTubeExtractor.extractor.waitFor();
		Redwood.player.waitFor();
		final String b = Redwood.player_url.get();
		final String segmentToRemove = StringsUtil.substringBetweenO(b, "/player_", "/base.js");
		final String s = b.replace("/player_" + segmentToRemove, "").replace("base.js", "www-player.css");
		final String n = HttpClient.getString().url(s).timeout(Duration.ofSeconds(60)).create().dataThenClose();
		player.set(n);
		final String ur = "/" + s.split(ID_SPLIT_PATTERN)[1];
		Redwood.log.info("[Redwood] player-css url: " + ur);
		return new RedwoodPlayerCSSFile();
	}

	private static final variable<String> player = new variable<String>();

	@SuppressWarnings("resource")
	@Override
	public Response onRequest(final Request request) {
		if (!Redwood.ENABLE_AUTO_UPDATING)
			return new Response(200, FileUtil.getResourceStream(RedwoodResource.class, "player.css")).setCustomMime("text/css");
		try {
			return new Response(200, createStream(player.get())).setCustomMime("text/css");
		} catch (Exception e) {
			JVM.errorln(e);
			return new Response(503);
		}
	}

	private static final String ID_SPLIT_PATTERN = Pattern.quote(".com/");

	public static String id() {
		YouTubeExtractor.extractor.waitFor();
		Redwood.player.waitFor();
		final String s = Redwood.player_url.get().replace("base.js", "webgl.js");
		try {
			return "/" + s.split(ID_SPLIT_PATTERN)[1];
		} catch (Exception e) {
			Redwood.log.error("Failed to get webjs URL! [player_url: " + Redwood.player_url.get() + "]", e);
			return null;
		}
	}

}
